package com.gan.simple_init.controller;

import com.alibaba.fastjson.JSONObject;
import com.gan.simple_init.common.base.ResponseResult;
import com.gan.simple_init.common.base.RestResultGenerator;
import com.gan.simple_init.common.constant.FileConstant;
import com.gan.simple_init.common.exception.BusinessException;
import com.gan.simple_init.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 文件上传/下载基类，有用到相关功能的controller继承即可
 * @author gbw
 * @date 2023/8/24
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    FileUtils fileUtils;


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping(value = "/download",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void fileDownload(String extractFileName,Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(extractFileName))
            {
                throw new BusinessException(String.format("文件名称(%s)非法，不允许下载。 ", extractFileName));
            }
            // 实际下载路径
            String filePath = FileConstant.DOWNLOAD_PATH + File.separator + extractFileName;

            int begin = extractFileName.lastIndexOf('/');
            int mid = extractFileName.lastIndexOf('_');
            int end = extractFileName.lastIndexOf('.');

            String fileName = extractFileName.substring(begin + 1,mid) + extractFileName.substring(end);

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 文件上传请求（单个）
     */
    @PostMapping("/upload")
    public ResponseResult<?> uploadFile(@RequestPart("file") MultipartFile file)
    {
        try
        {
            // 上传并返回新文件名称
            String fileName = fileUtils.upload(file);
            String url = FileConstant.HOST + FileConstant.RESOURCE_PREFIX + fileName;

            HashMap<String, Object> map = new HashMap<>(4);
            map.put("url", url);
            map.put("newFileName", FileUtils.getName(fileName));
            map.put("extractFileName", fileName);
            map.put("originalFilename", file.getOriginalFilename());
            return RestResultGenerator.success(new JSONObject(map),"上传成功!");
        }
        catch (Exception e)
        {
            return RestResultGenerator.error(e.getMessage());
        }
    }


    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public ResponseResult<?> uploadFiles(@RequestPart("files") MultipartFile[] files)
    {
        try
        {
            // 上传文件路径
            List<String> urls = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            List<String> extractFileNames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                String fileName = fileUtils.upload(file);
                String newFileName = FileUtils.getName(fileName);
                String url = FileConstant.HOST + FileConstant.RESOURCE_PREFIX + fileName;
                String originalFilename = file.getOriginalFilename();

                urls.add(url);
                newFileNames.add(newFileName);
                originalFilenames.add(originalFilename);
                extractFileNames.add(fileName);
            }

            HashMap<String, Object> map = new HashMap<>(4);
            map.put("urls", urls);
            map.put("newFileNames", newFileNames);
            map.put("originalFilenames", originalFilenames);
            map.put("extractFileNames", extractFileNames);
            return RestResultGenerator.success(new JSONObject(map),"上传成功!");
        }
        catch (Exception e)
        {
            return RestResultGenerator.error(e.getMessage());
        }
    }

}
